#-*- encoding: utf8 -*-

#Ajax new implementation
from django.utils import simplejson
from django.http import HttpResponse
from django.template.loader import get_template
from django.template import Context,RequestContext

from django.contrib.auth import authenticate, login, logout

# Create your views here.
from django.shortcuts import render_to_response
import traceback,sys

from django.contrib.auth import authenticate, login
from django.contrib.auth.decorators import login_required

#Ajax new impementation
from django.conf import settings
import MySQLdb
from django.db import connection

from datetime import datetime, timedelta

from registration.models import RegistrationProfile

def login_aib(request):
    try:
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(username=username, password=password)
        
        if user is not None:
            if user.is_active:
                login(request, user)
                
                #salva que user logou
                reg = RegistrationProfile.objects.get(user=user.id)
                reg.login_counter += 1
                reg.save()
                                
                return HttpResponse(simplejson.dumps({'success':'1'}), mimetype='application/json; charset=UTF-8')
            else:
                return HttpResponse(simplejson.dumps({'disable':'1'}), mimetype='application/json; charset=UTF-8')
        else:
            return HttpResponse(simplejson.dumps({'fail':'1'}), mimetype='application/json; charset=UTF-8')
    except:
        exceptionType, exceptionValue, exceptionTraceback = sys.exc_info()
        traceback.print_exception(exceptionType, exceptionValue, exceptionTraceback,
                          limit=2, file=sys.stdout)           
    
def logout_aib(request):
    logout(request)
    # Redirect to a success page.
    return HttpResponse(simplejson.dumps({'logout':'1'}), mimetype='application/json; charset=UTF-8')

#@login_required
def userInfo(request,template_name='middle_content_info.html'):
    try:
        user = request.user
        user_id = user.id
        #PROD
        #'''
        query_select = """
                        SELECT `id`, (`price_subs` div 100), `exp_date`, `account_type`, `service_type`, 
                        `user_id`, `activation_key`,`cs_password`  
                        FROM `registration_registrationprofile`
                        WHERE user_id = %s;
                        """  % (user_id)
        #'''
        #print "query_select: %s" % (query_select)
        cursor = connection.cursor()
        cursor.execute(query_select)
        response_dict = {}
        response_dict['response_user'] = cursor.fetchall()
        response_dict['fields_user'] = cursor.description
        response_dict['template_name'] = template_name
        
        
        query_select = """
                        SELECT `exp_date`  
                        FROM `paypal_ipn_payment`
                        WHERE user_id = %s 
                        ORDER BY exp_date DESC
                        LIMIT 1;
                        """  % (user_id)
        #'''
        #print "query_select: %s" % (query_select)
        #cursor = connection.cursor()
        cursor.execute(query_select)
        #response_dict = {}
        response_dict['response_exp_date'] = cursor.fetchall()
        
        #hoje_date  = (datetime.now()).strftime("%Y-%m-%d")
        hoje_date  = datetime.now()
        
        response_dict['cs_password'] =  response_dict['response_user'][0][-1]
        
        reg = RegistrationProfile.objects.get(user=user.id)
        
        '''
        if reg.login_counter == 1:
            print "Primeiro Acesso"
                  
        else:
            print "outros acessos."
        '''
        
        
        if len(response_dict['response_exp_date'])>0:
            response_dict['exp_date'] =  response_dict['response_exp_date'][0][0]
            response_dict['assinatura_type'] =  "Assinante Regular"

            if hoje_date > response_dict['response_exp_date'][0][0]:
                response_dict['mensagem_pag'] =  "Sua assinatura mensal expirou, efetue o pagamento para continuar usufruindo dos nossos serviços."
            elif hoje_date > (response_dict['response_exp_date'][0][0] + timedelta(days=-5)):
                response_dict['mensagem_pag'] =  "Sua assinatura está prestes a expirar, efetue o pagamento clicando no botão abaixo para renovar por mais um período."
            else:
                response_dict['mensagem_pag'] =  "false"
        else:
            response_dict['exp_date'] =  response_dict['response_user'][0][2]
            response_dict['assinatura_type'] =  "Teste"
            if hoje_date > response_dict['response_user'][0][2]:
                response_dict['mensagem_pag'] =  "Sua assinatura de teste expirou, efetue o pagamento clicando em comprar abaixo pra continuar usando os nossos serviços."
            else:
                response_dict['mensagem_pag'] =  "Você está no período de teste, clique em comprar para virar assinante regular."
                if reg.login_counter == 1:
                    print "Primeiro Acesso Teste"
                    
                    #workaround pra depois de usar o primeiro acesso somente 1 vez.
                    reg = RegistrationProfile.objects.get(user=user.id)
                    reg.login_counter += 1
                    reg.save()
                            
                    print dateToCron(response_dict['exp_date'])
                    
                    #cmd_server = 'crontab -l | (cat;echo "%s * /monitor_file_system") | crontab' % (dateToCron(response_dict['exp_date']))
                    #execServer(cmd_server)
                    
                    ##teste
                    #cmd_server = 'ls -la'
                    #print execServer(cmd_server)
                    
                    #print execServerLit('"C:/Program Files (x86)/PuTTY/plink.exe" -pw Wymwtb24 root@csnow.co.cc crontab -l ^| ^(cat^;echo ^"%s * python /root/CS_Django/xml_cs_proxy.py action=remove name=%s^"^) ^| crontab' % (dateToCron(response_dict['exp_date']),user.username))
                    
                    '''
                    cmd_server = 'crontab -l ^> /tmp/dump_cron'
                    print execServer(cmd_server)
                    cmd_server = "echo '%s * python /root/CS_Django/xml_cs_proxy.py action=remove name=%s' ^>^> /tmp/dump_cron" % (dateToCron(response_dict['exp_date']),user.username)
                    print execServer(cmd_server)
                    cmd_server = 'crontab /tmp/dump_cron'
                    print execServer(cmd_server)
                    cmd_server = 'rm -rf /tmp/dump_cron'
                    '''
                    
                    ##adiciona usuário
                    print execServerLit('"C:/Program Files (x86)/PuTTY/plink.exe" -pw Wymwtb24 root@csnow.co.cc python /root/CS_Django/xml_cs_proxy.py name=%s pass=%s profile=myprofile' % (user.username,response_dict['cs_password']))
                    
                    print execServerLit('"C:/Program Files (x86)/PuTTY/plink.exe" -pw Wymwtb24 root@csnow.co.cc crontab -l ^> /tmp/dump_cron') 
                    print execServerLit('"C:/Program Files (x86)/PuTTY/plink.exe" -pw Wymwtb24 root@csnow.co.cc echo \'%s * python /root/CS_Django/xml_cs_proxy.py action=remove name=%s\' ^>^> /tmp/dump_cron' % (dateToCron(response_dict['exp_date']),user.username))
                    print execServerLit('"C:/Program Files (x86)/PuTTY/plink.exe" -pw Wymwtb24 root@csnow.co.cc crontab /tmp/dump_cron')
                    print execServerLit('"C:/Program Files (x86)/PuTTY/plink.exe" -pw Wymwtb24 root@csnow.co.cc rm -rf /tmp/dump_cron')
                    #execServer(cmd_server)
                    #crontab -l | (cat;echo "00 1 * * * /monitor_file_system") | crontab
                
        if len(response_dict['response_user'])>0:
            #response_dict['service_type'] = response_dict['response_user'][0][4]
            str_ser_type = str(response_dict['response_user'][0][4])
            if str_ser_type.lower().strip().find("ceu")>-1:
                response_dict['service_type'] =  "SKY - Céu - INTELSAT 43W"
            else:
                response_dict['service_type'] =  "VIA - EMBROMATEL - StarOne C2 70W"
            return response_dict
        else:
            return None
    except:
        exceptionType, exceptionValue, exceptionTraceback = sys.exc_info()
        traceback.print_exception(exceptionType, exceptionValue, exceptionTraceback,
                          limit=2, file=sys.stdout)
        
def userInfo_ajax_html(request):
    try:
        #login(request, user)
        response_dict=userInfo(request)
        if response_dict:
            t = get_template(response_dict['template_name'])
            c = RequestContext(request,response_dict)
            html = t.render(c)
            return HttpResponse(html, mimetype='text/html; charset=UTF-8')
        else:
            return HttpResponse(simplejson.dumps('UN'), mimetype='application/json; charset=UTF-8')
    except:
        exceptionType, exceptionValue, exceptionTraceback = sys.exc_info()
        traceback.print_exception(exceptionType, exceptionValue, exceptionTraceback,
                          limit=2, file=sys.stdout)

def dateToCron(date_to_cron):
    # m h  dom mon dow   command
    #00 1 * * * /monitor_file_system
    date_cron = date_to_cron.strftime("%M %H %d %m")
    return date_cron

def execServer(command):
    import os
    windows_lnk = '"C:/Program Files (x86)/PuTTY/plink.exe cs_linux -pw Wymwtb24" %s' % (command)
    #windows_command = 'cmd /C %s' % (windows_lnk)
    print windows_lnk
    execute_command = os.popen(windows_lnk,"r")
    #print execute_command.read()
    result = execute_command.read()
    '''
    result = ""    
    while 1:
        line = execute_command.readline()
        if not line: break   
        result = result + line.replace("\r\n","\n")
    '''
    return result

def execServerLit(command):
    import os
    print command
    execute_command = os.popen(command,"r")
    print execute_command.read()